<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 什么是XML？XML 指可扩展标记语言（eXtensible Markup Language），标准通用标记语言的子集，是一种用于标记电子文件使其具有结构性的标记语言。 XML 被设计用来传输和存储数据。XML是一套定义语义标记的规则，这些标记将文档分成许多部件并对这些部件加以标识。它也是元标记语言，即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。pytho">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Python-学习(十)--数据解析">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Python/Python-学习(十)--数据解析/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 什么是XML？XML 指可扩展标记语言（eXtensible Markup Language），标准通用标记语言的子集，是一种用于标记电子文件使其具有结构性的标记语言。 XML 被设计用来传输和存储数据。XML是一套定义语义标记的规则，这些标记将文档分成许多部件并对这些部件加以标识。它也是元标记语言，即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。pytho">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-dd6be1f06e90a0c2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-0c4b855cbc67e19c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-ceaf8bcbefb825fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-52444654bfc58092.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-97f61d86e3be7c8c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-d0ae4f909455df5b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-2eb99b90457b458c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-118a58a3637180ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:32:23.497Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python-学习(十)--数据解析">
<meta name="twitter:description" content="####1. 什么是XML？XML 指可扩展标记语言（eXtensible Markup Language），标准通用标记语言的子集，是一种用于标记电子文件使其具有结构性的标记语言。 XML 被设计用来传输和存储数据。XML是一套定义语义标记的规则，这些标记将文档分成许多部件并对这些部件加以标识。它也是元标记语言，即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。pytho">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-dd6be1f06e90a0c2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Python/Python-学习(十)--数据解析/"/>





  <title>Python-学习(十)--数据解析 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Python/Python-学习(十)--数据解析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python-学习(十)--数据解析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 什么是XML？<br>XML 指可扩展标记语言（e<strong>X</strong>tensible <strong>M</strong>arkup <strong>L</strong>anguage），标准通用标记语言的子集，是一种用于标记电子文件使其具有结构性的标记语言。 XML 被设计用来传输和存储数据。XML是一套定义语义标记的规则，这些标记将文档分成许多部件并对这些部件加以标识。它也是元标记语言，即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。<br>python对XML的解析<br>常见的XML编程接口有DOM和SAX，这两种接口处理XML文件的方式不同，当然使用场合也不同。<br><a id="more"></a></p>
<p><strong>python有三种方法解析XML，SAX，DOM，以及ElementTree:</strong></p>
<ul>
<li>SAX (simple API for XML )<br>python 标准库包含SAX解析器，SAX用事件驱动模型，通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。</li>
<li>DOM(Document Object Model)<br>将XML数据在内存中解析成一个树，通过对树的操作来操作XML。</li>
</ul>
<p>下面用到的movies.xml内容：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">&lt;collection shelf=&quot;New Arrivals&quot;&gt;</span><br><span class="line">&lt;movie title=&quot;Enemy Behind&quot;&gt;</span><br><span class="line">   &lt;type&gt;War, Thriller&lt;/type&gt;</span><br><span class="line">   &lt;format&gt;DVD&lt;/format&gt;</span><br><span class="line">   &lt;year&gt;2003&lt;/year&gt;</span><br><span class="line">   &lt;rating&gt;PG&lt;/rating&gt;</span><br><span class="line">   &lt;stars&gt;10&lt;/stars&gt;</span><br><span class="line">   &lt;description&gt;Talk about a US-Japan war&lt;/description&gt;</span><br><span class="line">&lt;/movie&gt;</span><br><span class="line">&lt;movie title=&quot;Transformers&quot;&gt;</span><br><span class="line">   &lt;type&gt;Anime, Science Fiction&lt;/type&gt;</span><br><span class="line">   &lt;format&gt;DVD&lt;/format&gt;</span><br><span class="line">   &lt;year&gt;1989&lt;/year&gt;</span><br><span class="line">   &lt;rating&gt;R&lt;/rating&gt;</span><br><span class="line">   &lt;stars&gt;8&lt;/stars&gt;</span><br><span class="line">   &lt;description&gt;A schientific fiction&lt;/description&gt;</span><br><span class="line">&lt;/movie&gt;</span><br><span class="line">   &lt;movie title=&quot;Trigun&quot;&gt;</span><br><span class="line">   &lt;type&gt;Anime, Action&lt;/type&gt;</span><br><span class="line">   &lt;format&gt;DVD&lt;/format&gt;</span><br><span class="line">   &lt;episodes&gt;4&lt;/episodes&gt;</span><br><span class="line">   &lt;rating&gt;PG&lt;/rating&gt;</span><br><span class="line">   &lt;stars&gt;10&lt;/stars&gt;</span><br><span class="line">   &lt;description&gt;Vash the Stampede!&lt;/description&gt;</span><br><span class="line">&lt;/movie&gt;</span><br><span class="line">&lt;movie title=&quot;Ishtar&quot;&gt;</span><br><span class="line">   &lt;type&gt;Comedy&lt;/type&gt;</span><br><span class="line">   &lt;format&gt;VHS&lt;/format&gt;</span><br><span class="line">   &lt;rating&gt;PG&lt;/rating&gt;</span><br><span class="line">   &lt;stars&gt;2&lt;/stars&gt;</span><br><span class="line">   &lt;description&gt;Viewable boredom&lt;/description&gt;</span><br><span class="line">&lt;/movie&gt;</span><br><span class="line">&lt;/collection&gt;</span><br></pre></td></tr></table></figure></p>
<p>####2. SAX解析xml<br>1). SAX是一种基于事件驱动的API。利用SAX解析XML文档牵涉到两个部分:解析器和事件处理器。解析器负责读取XML文档,并向事件处理器发送事件,如元素开始跟元素结束事件;而事件处理器则负责对事件作出相应,对传递的XML数据进行处理。<br>1、对大型文件进行处理；<br>2、只需要文件的部分内容，或者只需从文件中得到特定信息。<br>3、想建立自己的对象模型的时候。</p>
<p>2). 在python中使用sax方式处理xml要先引入xml.sax中的parse函数，还有xml.sax.handler中的ContentHandler。<br>ContentHandler类方法介绍</p>
<ul>
<li>characters(content)方法<br>调用时机：<br>1&gt;. 从行开始，遇到标签之前，存在字符，content的值为这些字符串。<br>2&gt;. 从一个标签，遇到下一个标签之前， 存在字符，content的值为这些字符串。<br>3&gt;. 从一个标签，遇到行结束符之前，存在字符，content的值为这些字符串。<br>4&gt;. 标签可以是开始标签，也可以是结束标签。</li>
<li>startDocument()方法: 文档启动的时候调用。</li>
<li>endDocument()方法: 解析器到达文档结尾时调用。</li>
<li>startElement(name, attrs)方法: 遇到XML开始标签时调用，name是标签的名字，attrs是标签的属性值字典。</li>
<li>endElement(name)方法: 遇到XML结束标签时调用。</li>
</ul>
<p>3). make_parser方法<br>以下方法创建一个新的解析器对象并返回。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">xml.sax.make_parser( [parser_list] )</span><br></pre></td></tr></table></figure></p>
<p>参数说明:<br>parser_list - 可选参数，解析器列表</p>
<p>4). parser方法<br>以下方法创建一个 SAX 解析器并解析xml文档：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">xml.sax.parse( xmlfile, contenthandler[, errorhandler])</span><br></pre></td></tr></table></figure></p>
<p>参数说明:<br>xmlfile - xml文件名<br>contenthandler - 必须是一个ContentHandler的对象<br>errorhandler - 如果指定该参数，errorhandler必须是一个SAX ErrorHandler对象</p>
<p>5). parseString方法<br>parseString方法创建一个XML解析器并解析xml字符串：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">xml.sax.parseString(xmlstring, contenthandler[, errorhandler])</span><br></pre></td></tr></table></figure></p>
<p>参数说明:<br>xmlstring - xml字符串<br>contenthandler - 必须是一个ContentHandler的对象<br>errorhandler - 如果指定该参数，errorhandler必须是一个SAX ErrorHandler对象</p>
<p>6). 示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">import xml.sax</span><br><span class="line"></span><br><span class="line">class MovieHandler(xml.sax.ContentHandler):</span><br><span class="line">	&quot;&quot;&quot;docstring for MovieHandler&quot;&quot;&quot;</span><br><span class="line">	def __init__(self):</span><br><span class="line">		super(MovieHandler, self).__init__()</span><br><span class="line">		self.CurrendData = &quot;&quot;</span><br><span class="line">		self.type = &quot;&quot;</span><br><span class="line">		self.format = &quot;&quot;</span><br><span class="line">		self.year = &quot;&quot;</span><br><span class="line">		self.rating = &quot;&quot;</span><br><span class="line">		self.stars = &quot;&quot;</span><br><span class="line">		self.description = &quot;&quot;</span><br><span class="line"></span><br><span class="line">	# 元素开始调用</span><br><span class="line">	def startElement(self, tag, attributes):</span><br><span class="line">		self.CurrendData = tag</span><br><span class="line">		if tag == &quot;movie&quot;:</span><br><span class="line">			print(&quot;******Movie******&quot;)</span><br><span class="line">			title = attributes[&quot;title&quot;]</span><br><span class="line">			print(&quot;Title: &quot;, title)</span><br><span class="line">			pass</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">	# 元素结束调用</span><br><span class="line">	def endElement(self, tag):</span><br><span class="line">		if self.CurrendData == &quot;type&quot;:</span><br><span class="line">			print(&quot;Type: &quot;, self.type)</span><br><span class="line">		elif self.CurrendData == &quot;format&quot;:</span><br><span class="line">			print(&quot;Format: &quot;, self.format)</span><br><span class="line">		elif self.CurrendData == &quot;year&quot;:</span><br><span class="line">			print(&quot;Year: &quot;, self.year)</span><br><span class="line">		elif self.CurrendData == &quot;rating&quot;:</span><br><span class="line">			print(&quot;Rating: &quot;, self.rating)</span><br><span class="line">		elif self.CurrendData == &quot;stars&quot;:</span><br><span class="line">			print(&quot;Stars: &quot;, self.stars)</span><br><span class="line">		elif self.CurrendData == &quot;description&quot;:</span><br><span class="line">			print(&quot;Description: &quot;, self.description)</span><br><span class="line">		self.CurrendData = &quot;&quot;</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">	# 读取字符时调用</span><br><span class="line">	def characters(self, content):</span><br><span class="line">		if self.CurrendData == &quot;type&quot;:</span><br><span class="line">			self.type = content</span><br><span class="line">		elif self.CurrendData == &quot;format&quot;:</span><br><span class="line">			self.format = content</span><br><span class="line">		elif self.CurrendData == &quot;year&quot;:</span><br><span class="line">			self.year = content</span><br><span class="line">		elif self.CurrendData == &quot;rating&quot;:</span><br><span class="line">			self.rating = content</span><br><span class="line">		elif self.CurrendData == &quot;stars&quot;:</span><br><span class="line">			self.stars = content</span><br><span class="line">		elif self.CurrendData == &quot;description&quot;:</span><br><span class="line">			self.description = content</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">if (__name__ == &quot;__main__&quot;) :</span><br><span class="line">	# 创建一个XMLReader</span><br><span class="line">	parser = xml.sax.make_parser()</span><br><span class="line">	# 关闭命名空间</span><br><span class="line">	parser.setFeature(xml.sax.handler.feature_namespaces, 0)</span><br><span class="line">	# 重写 ContextHandler</span><br><span class="line">	handler = MovieHandler()</span><br><span class="line">	parser.setContentHandler(handler)</span><br><span class="line"></span><br><span class="line">	parser.parse(&quot;movies.xml&quot;)</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-dd6be1f06e90a0c2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>####3. Dom解析xml<br>文件对象模型（Document Object Model，简称DOM），是W3C组织推荐的处理可扩展置标语言的标准编程接口。一个 DOM 的解析器在解析一个 XML 文档时，一次性读取整个文档，把文档中所有元素保存在内存中的一个树结构里，之后你可以利用DOM 提供的不同的函数来读取或修改文档的内容和结构，也可以把修改过的内容写入xml文件。python中用xml.dom.minidom来解析xml文件.</p>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">from xml.dom.minidom import parse</span><br><span class="line">import xml.dom.minidom</span><br><span class="line"></span><br><span class="line"># 使用minidom解析器打开XML文档</span><br><span class="line">DOMTree = xml.dom.minidom.parse(&quot;movies.xml&quot;)</span><br><span class="line"></span><br><span class="line"># 获取collection节点</span><br><span class="line">collection = DOMTree.documentElement</span><br><span class="line">if collection.hasAttribute(&quot;shelf&quot;):</span><br><span class="line">	print(&quot;Root element: %s&quot; % collection.getAttribute(&quot;shelf&quot;))</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line"># 在集合获取所有电影</span><br><span class="line">movies = collection.getElementsByTagName(&quot;movie&quot;)</span><br><span class="line"></span><br><span class="line"># 打印每部电影的详细信息</span><br><span class="line">for movie in movies:</span><br><span class="line">	print(&quot;*******Movie********&quot;)</span><br><span class="line">	if movie.hasAttribute(&quot;title&quot;):</span><br><span class="line">		print(&quot;Title: %s&quot; % movie.getAttribute(&quot;title&quot;))</span><br><span class="line">		pass</span><br><span class="line">	pass</span><br><span class="line">	type = movie.getElementsByTagName(&quot;type&quot;)[0]</span><br><span class="line">	print(&quot;Type: %s&quot; % type.childNodes[0].data)</span><br><span class="line">	format = movie.getElementsByTagName(&quot;format&quot;)[0]</span><br><span class="line">	print(&quot;Format: %s&quot; % format.childNodes[0].data)</span><br><span class="line">	rating = movie.getElementsByTagName(&quot;rating&quot;)[0]</span><br><span class="line">	print(&quot;Rating: %s&quot; % rating.childNodes[0].data)</span><br><span class="line">	description = movie.getElementsByTagName(&quot;description&quot;)[0]</span><br><span class="line">	print(&quot;Description: %s&quot; % description.childNodes[0].data)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-0c4b855cbc67e19c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####4. JSON解析<br>JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。<br>Python3 中可以使用 json 模块来对 JSON 数据进行编解码，它包含了两个函数：</p>
<ul>
<li>json.dumps(): 对数据进行编码。</li>
<li>json.loads(): 对数据进行解码。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">import json</span><br><span class="line"># 字典</span><br><span class="line">data = &#123;</span><br><span class="line">	&apos;no&apos; : 1,</span><br><span class="line">	&apos;name&apos; : &apos;mazaiting&apos;,</span><br><span class="line">	&apos;url&apos; : &apos;https://www.jianshu.com/u/5d2cb4bfeb15&apos;</span><br><span class="line">&#125;</span><br><span class="line"># 将python字典类型装换为JSON对象</span><br><span class="line">json_str = json.dumps(data)</span><br><span class="line">print(&quot;Python 原始数据: &quot;, repr(data))</span><br><span class="line">print(&quot;JSON 对象: &quot;, json_str)</span><br><span class="line"></span><br><span class="line"># 将JSON对象转化为Python字典</span><br><span class="line">data2 = json.loads(json_str)</span><br><span class="line">print(&quot;data2[&apos;name&apos;]: &quot;, data2[&apos;name&apos;])</span><br><span class="line">print(&quot;data2[&apos;url&apos;]: &quot;, data2[&apos;url&apos;])</span><br></pre></td></tr></table></figure>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-ceaf8bcbefb825fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>####5. 时间<br>Python 程序能用很多方式处理日期和时间，转换日期格式是一个常见的功能。Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。时间间隔是以秒为单位的浮点小数。每个时间戳都以自从1970年1月1日午夜（历元）经过了多长时间来表示。Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳。</p>
<p>1). 获取当前时间戳<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># 引入time模块</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">ticks = time.time()</span><br><span class="line">print(&quot;当前时间戳为：&quot;, ticks)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-52444654bfc58092.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>
<p>2). 时间元组<br>很多Python函数用一个元组装起来的9组数字处理时间:</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>字段</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>4位数年</td>
<td>2008</td>
</tr>
<tr>
<td>1</td>
<td>月</td>
<td>1 到 12</td>
</tr>
<tr>
<td>2</td>
<td>日</td>
<td>1到31</td>
</tr>
<tr>
<td>3</td>
<td>小时</td>
<td>0到23</td>
</tr>
<tr>
<td>4</td>
<td>分钟</td>
<td>0到59</td>
</tr>
<tr>
<td>5</td>
<td>秒</td>
<td>0到61 (60或61 是闰秒)</td>
</tr>
<tr>
<td>6</td>
<td>一周的第几日</td>
<td>0到6 (0是周一)</td>
</tr>
<tr>
<td>7</td>
<td>一年的第几日</td>
<td>1到366 (儒略历)</td>
</tr>
<tr>
<td>8</td>
<td>夏令时</td>
<td>-1, 0, 1, -1是决定是否为夏令时的旗帜</td>
</tr>
</tbody>
</table>
<p>上述也就是struct_time元组。这种结构具有如下属性：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>属性</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>tm_year</td>
<td>2008</td>
</tr>
<tr>
<td>1</td>
<td>tm_mon</td>
<td>1 到 12</td>
</tr>
<tr>
<td>2</td>
<td>tm_mday</td>
<td>1 到 31</td>
</tr>
<tr>
<td>3</td>
<td>tm_hour</td>
<td>0 到 23</td>
</tr>
<tr>
<td>4</td>
<td>tm_min</td>
<td>0 到 59</td>
</tr>
<tr>
<td>5</td>
<td>tm_sec</td>
<td>0 到 61 (60或61 是闰秒)</td>
</tr>
<tr>
<td>6</td>
<td>tm_wday</td>
<td>0到6 (0是周一)</td>
</tr>
<tr>
<td>7</td>
<td>tm_yday</td>
<td>一年中的第几天，1 到 366</td>
</tr>
<tr>
<td>8</td>
<td>tm_isdst</td>
<td>是否为夏令时，值有：1(夏令时)、0(不是夏令时)、-1(未知)，默认 -1</td>
</tr>
</tbody>
</table>
<p>3). 获取当前时间<br>从返回浮点数的时间辍方式向时间元组转换，只要将浮点数传递给如localtime之类的函数。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line"></span><br><span class="line">localtime = time.localtime(time.time())</span><br><span class="line">print(&quot;本地时间为：&quot;, localtime)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-97f61d86e3be7c8c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"></p>
<p>4). 获取格式化的时间<br>你可以根据需求选取各种格式，但是最简单的获取可读的时间模式的函数是asctime()<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line"></span><br><span class="line">localtime = time.asctime(time.localtime(time.time()))</span><br><span class="line">print(&quot;本地时间为：&quot;, localtime)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-d0ae4f909455df5b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
<p>5). 格式化日期<br>我们可以使用 time 模块的 strftime 方法来格式化日期：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">time.strftime(format[, t])</span><br></pre></td></tr></table></figure></p>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line"></span><br><span class="line"># 格式化成2016-03-20 11:45:39</span><br><span class="line">print(time.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;, time.localtime()))</span><br><span class="line"></span><br><span class="line"># 格式化成Wed Apr 11 16:56:32 2018形式</span><br><span class="line">print(time.strftime(&quot;%a %b %d %H:%M:%S %Y&quot;, time.localtime()))</span><br><span class="line"></span><br><span class="line"># 将格式字符串转换为时间戳</span><br><span class="line">a = &quot;Wed Apr 11 16:56:32 2018&quot;</span><br><span class="line">print(time.mktime(time.strptime(a, &quot;%a %b %d %H:%M:%S %Y&quot;)))</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-2eb99b90457b458c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>6). python中时间日期格式化符号：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">%y 两位数的年份表示（00-99）</span><br><span class="line">%Y 四位数的年份表示（000-9999）</span><br><span class="line">%m 月份（01-12）</span><br><span class="line">%d 月内中的一天（0-31）</span><br><span class="line">%H 24小时制小时数（0-23）</span><br><span class="line">%I 12小时制小时数（01-12）</span><br><span class="line">%M 分钟数（00=59）</span><br><span class="line">%S 秒（00-59）</span><br><span class="line">%a 本地简化星期名称</span><br><span class="line">%A 本地完整星期名称</span><br><span class="line">%b 本地简化的月份名称</span><br><span class="line">%B 本地完整的月份名称</span><br><span class="line">%c 本地相应的日期表示和时间表示</span><br><span class="line">%j 年内的一天（001-366）</span><br><span class="line">%p 本地A.M.或P.M.的等价符</span><br><span class="line">%U 一年中的星期数（00-53）星期天为星期的开始</span><br><span class="line">%w 星期（0-6），星期天为星期的开始</span><br><span class="line">%W 一年中的星期数（00-53）星期一为星期的开始</span><br><span class="line">%x 本地相应的日期表示</span><br><span class="line">%X 本地相应的时间表示</span><br><span class="line">%Z 当前时区的名称</span><br><span class="line">%% %号本身</span><br></pre></td></tr></table></figure></p>
<p>7). 日期<br>Calendar模块有很广泛的方法用来处理年历和月历.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># 获取某月日历</span><br><span class="line">import calendar</span><br><span class="line"></span><br><span class="line">cal = calendar.month(2018, 4)</span><br><span class="line">print(&quot;以下输出2016年1月份的日历：&quot;)</span><br><span class="line">print(cal)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-118a58a3637180ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(六)/" rel="next" title="Python-学习(六)">
                <i class="fa fa-chevron-left"></i> Python-学习(六)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(四)/" rel="prev" title="Python-学习(四)">
                Python-学习(四) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
